package zzxkj.blog.service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Service;
import zzxkj.blog.dao.UserDao;
import zzxkj.blog.pojo.User;
import zzxkj.blog.service.UserService;
import zzxkj.blog.utils.MD5Util;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    private final UserDao userDao;

    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    /**
     * 这里抛出的异常是shiro认证相关的异常
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        password = MD5Util.code(password);
        User user = userDao.queryByUsername(username);
        if (user == null) {
            //找不到用户异常
            throw new UnknownAccountException();
        }
        if (!password.equals(user.getPassword())) {
            //密码错误异常
            log.info("this worn?");
            throw new IncorrectCredentialsException();
        }
        return user;
    }

    @Override
    public User queryByUsername(String username) {
        return userDao.queryByUsername(username);
    }

    @Override
    public User queryByNickname(String nickname) {
        return userDao.queryByNickname(nickname);
    }

    @Override
    public Integer createUser(User user) {
        //MD5加密
        user.setPassword(MD5Util.code(user.getPassword()));
        User hadUser = userDao.queryByUsername(user.getUsername());
        if(hadUser != null){
            return null;
        }
        return userDao.createUser(user);
    }

    @Override
    public Boolean isAdminUser(String username) {
        return userDao.isAdminUser(username);
    }

}
